#!/usr/bin/env python
# srt-split.py: split srt files containing Chinese and English

import sys, codecs, os

encoding = "utf-8"

def output(fp, line):
    fp.write(line.encode(encoding))

def is_cjk_char(x):
    # Punct & Radicals
    if x >= 0x2e80 and x <= 0x33ff:
        return 1

    # Fullwidth Latin Characters
    if x >= 0xff00 and x <= 0xffef:
        return 1

    # CJK Unified Ideographs &
    # CJK Unified Ideographs Extension A
    if x >= 0x4e00 and x <= 0x9fbb:
        return 1
    # CJK Compatibility Ideographs
    if x >= 0xf900 and x <= 0xfad9:
        return 1

    # CJK Unified Ideographs Extension B
    if x >= 0x20000 and x <= 0x2a6d6:
        return 1

    # CJK Compatibility Supplement
    if x >= 0x2f8000 and x <= 0x2fa1d:
        return 1

    return 0

def contain_cjk_char(line):
    # print "@: %s" % (line.encode("utf-8")) 

    for ch in line:
       if is_cjk_char(ord(ch)):
           return 1

    return 0

if len(sys.argv) < 2:
    print "usage: %s <file.srt>" % sys.argv[0]
    sys.exit(1)

srt_path = sys.argv[1]

if os.path.isfile(srt_path) != True:
    print "File %s does not exist." % srt_path
    sys.exit(1)

srt_file = codecs.open(srt_path, encoding='utf-8')
chs_out_file = sys.stdout
eng_out_file = sys.stderr

(BOTH, ENG, CHS) = range(3)

# We process the srt file like this:
# 
# At first, we are in BOTH state, in this state
# we simply output the line to both streams.
# 
# Then if line containing the time sequence is
# seen, like this:
# 00:00:01,000 --> 00:00:09,000
# We will enter ENG state after this line is 
# written.
# 
# In ENG state, the lines will only be output 
# to eng_out_file. But when a line containing
# CJK character is seen, we will enter CHS 
# state right away and output this line to 
# chs_out_file
# 
# In CHS state, only chs_out_file will get the 
# lines, but when a empty line is seen, we will
# siwth to BOTH state right away, and output t
# that empty line to both streams.

state = BOTH

for line in srt_file:
    if state == BOTH:
        output(chs_out_file, line)
        output(eng_out_file, line)

        if line.find(" --> ") != -1:
            state = ENG
    elif state == ENG:
        if contain_cjk_char(line):
            state = CHS
            output(chs_out_file, line)
        else:
            output(eng_out_file, line)
    else: # state == CHS
        if line == '\n' or line == '\r\n':
            state = BOTH
            output(eng_out_file, line)
        output(chs_out_file, line)

chs_out_file.close()
eng_out_file.close()

